package com.ruitu.mall_98_seller.mvp.presenter;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.content.FileProvider;

import com.google.gson.Gson;
import com.ruitu.arad.api.BaseResult;
import com.ruitu.arad.base.BasePresenter;
import com.ruitu.arad.util.AppUtils;
import com.ruitu.arad.util.ToastUtils;
import com.ruitu.mall_98_seller.dao.bean.HomeNum;
import com.ruitu.mall_98_seller.mvp.model.HomeModel;
import com.ruitu.mall_98_seller.support.util.FileProviderUtils;
import com.ruitu.mall_98_seller.ui.home.WorkFragment;
import com.ruitu.router_module.Logg;
import com.ruitu.router_module.bean.Version;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.jessyan.progressmanager.ProgressManager;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class HomePresenter {

    // 首页
    public static class HomeP extends BasePresenter<WorkFragment, HomeModel.HomeM> {
        public Disposable reqHomeNums(String comId) {
            return m.reqHomeNums(comId).subscribe(new Consumer<BaseResult>() {
                @Override
                public void accept(BaseResult result) throws Exception {
                    v.hideProgress();
                    Gson gson = new Gson();
                    HomeNum homeNum = gson.fromJson(result.getMsg(), HomeNum.class);
                    v.onReqComplete(1, true, homeNum);
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) throws Exception {
                    v.hideProgress();
                    throwable.printStackTrace();
                }
            });
        }

        public Disposable reqNewVersion(String type, final boolean showMsg) {
            return m.reqNewVersion(type).subscribe(new Consumer<BaseResult<Version>>() {
                @Override
                public void accept(BaseResult<Version> result) throws Exception {
                    v.hideProgress();
                    if (result.isSuccess()) {
                        if (null != result.getData()) {
                            if (AppUtils.getAppVersionCode() < result.getData().getCode()) {
                                // 有新版本
                                v.onReqComplete(2, true, result.getData());
                            } else {
                                if (showMsg) {
                                    ToastUtils.showShortSafe("已是最新版本");
                                }
                            }
                        } else {
                            if (showMsg) {
                                ToastUtils.showShortSafe("已是最新版本");
                            }
                        }
                    } else {
                        if (showMsg) {
                            ToastUtils.showShortSafe(result.getMsg());
                        }
                    }
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) throws Exception {
                    v.hideProgress();
                    throwable.printStackTrace();
                }
            });
        }

        public void downloadApk(final OkHttpClient mOkHttpClient, final String mDownloadUrl) {
            // rxjava + okhttp 下载
//            return m.downloadApk(mDownloadUrl).subscribe(new Consumer<ResponseBody>() {
//                @Override
//                public void accept(ResponseBody resBody) throws Exception {
//                    Logg.i(resBody.string());
//                    InputStream is = resBody.byteStream();
//                    File file = new File(activity.getExternalCacheDir(), "seller.apk");
//                    writeFile(mDownloadUrl, is, file);
//                }
//            }, new Consumer<Throwable>() {
//                @Override
//                public void accept(Throwable throwable) throws Exception {
//                    throwable.printStackTrace();
//                    ProgressManager.getInstance().notifyOnErorr(mDownloadUrl, (Exception) throwable);
//                }
//            });

            // retrofit下载
//            Retrofit retrofit = new Retrofit.Builder()
//                    .baseUrl(Config.URL)
//                    //通过线程池获取一个线程，指定callback在子线程中运行。
//                    .callbackExecutor(Executors.newSingleThreadExecutor())
//                    .build();
//            ApiService service = retrofit.create(ApiService.class);
//            Call<ResponseBody> call = service.download(mDownloadUrl);
//            call.enqueue(new Callback<ResponseBody>() {
////                @Override
////                public void onResponse(@NonNull Call<ResponseBody> call, @NonNull final Response<ResponseBody> response) {
////                    //将Response写入到从磁盘中，详见下面分析
////                    //注意，这个方法是运行在子线程中的
////                    writeResponseToDisk(path, response, downloadListener);
////                }
//
//                @Override
//                public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
//                    File file = new File(activity.getExternalCacheDir(), "seller.apk");
//                    writeFile(mDownloadUrl, response.body().byteStream(), file);
//                }
//
//                @Override
//                public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable throwable) {
//                    ProgressManager.getInstance().notifyOnErorr(mDownloadUrl, (Exception) throwable);
//                }
//            });

            // okhttp下载
//            final Thread thread = new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    try {
//                        Request request = new Request.Builder().url(mDownloadUrl).build();
//                        Response response = mOkHttpClient.newCall(request).execute();
//
//                        InputStream is = response.body().byteStream();
//                        //为了方便就不动态申请权限了,直接将文件放到CacheDir()中
//                        File file = new File(activity.getExternalCacheDir(), "seller.apk");
//                        FileOutputStream fos = new FileOutputStream(file);
////                        FileOutputStream fos = activity.openFileOutput("seller.apk", activity.MODE_PRIVATE);
//                        BufferedInputStream bis = new BufferedInputStream(is);
//                        byte[] buffer = new byte[1024];
//                        int len;
//                        while ((len = bis.read(buffer)) != -1) {
//                            fos.write(buffer, 0, len);
//                        }
//                        fos.flush();
//                        fos.close();
//                        bis.close();
//                        is.close();
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                        //当外部发生错误时,使用此方法可以通知所有监听器的 onError 方法
//                        ProgressManager.getInstance().notifyOnErorr(mDownloadUrl, e);
//                    }
//                }
//            });
//            thread.start();

            myThread = new MyThread(mOkHttpClient, mDownloadUrl);
            myThread.start();
        }

        class MyThread extends Thread {
            OkHttpClient mOkHttpClient;
            String mDownloadUrl;

            public MyThread(OkHttpClient mOkHttpClient, String mDownloadUrl) {
                this.mOkHttpClient = mOkHttpClient;
                this.mDownloadUrl = mDownloadUrl;
            }

            @Override
            public void run() {
                while (!isInterrupted()) {
                    try {
                        Request request = new Request.Builder().url(mDownloadUrl).build();
                        Response response = mOkHttpClient.newCall(request).execute();

                        InputStream is = response.body().byteStream();
                        //为了方便就不动态申请权限了,直接将文件放到CacheDir()中
                        File file = new File(activity.getExternalCacheDir(), "seller.apk");
                        FileOutputStream fos = new FileOutputStream(file);
//                        FileOutputStream fos = activity.openFileOutput("seller.apk", activity.MODE_PRIVATE);
                        BufferedInputStream bis = new BufferedInputStream(is);
                        byte[] buffer = new byte[1024];
                        int len;
                        while ((len = bis.read(buffer)) != -1) {
                            fos.write(buffer, 0, len);
                        }
                        fos.flush();
                        fos.close();
                        bis.close();
                        is.close();
                        break;
                    } catch (Exception e) {
                        e.printStackTrace();
                        //当外部发生错误时,使用此方法可以通知所有监听器的 onError 方法
                        ProgressManager.getInstance().notifyOnErorr(mDownloadUrl, e);
                        break;
                    }
                }
            }
        }

        private MyThread myThread;

        public void startMyThread(boolean b) {
            if (null != myThread) {
                if (!b) {
                    myThread.interrupt();
                }
            }
        }

        // 安装apk
        public void installApp() {
            File file = new File(activity.getExternalCacheDir() + "/seller.apk");
            //兼容8.0
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                boolean installAllowed = activity.getPackageManager().canRequestPackageInstalls();
                Logg.i("installAllowed = " + installAllowed);
                if (installAllowed) {
                    installApk(file);
                } else {
                    // 跳转到设置-允许安装未知来源-页面
                    Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + activity.getPackageName()));
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    activity.startActivity(intent);
                    installApk(file);
                }
            } else {
                installApk(file);
            }
        }

        private void installApk(File file) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            String type = "application/vnd.android.package-archive";
//            intent.setDataAndType(uri, type);
            FileProviderUtils.setIntentDataAndType(activity, intent, type, file, "com.ruitu.mall_98_seller.fileprovider");
            activity.startActivity(intent);
        }

        // 没有加入安卓8.0验证的安装方案
        public static void installApp(Context context, File appFile) {
            if (null == appFile) return;
            if (!appFile.exists()) return;
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            Uri uri;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                uri = FileProvider.getUriForFile(context, "com.ruitu.mall_98_seller.fileprovider", appFile);
            } else {
                uri = Uri.fromFile(appFile);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            }
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
            context.startActivity(intent);
        }
    }
}
